from django.shortcuts import render

# Create your views here.


import re
from django.db.models import Q
from rest_framework.response import Response
from rest_framework.views import APIView
# from utils.jwttool import tooljwt
from userapp.models import UserModel
from userapp.serializers import UserSerializer


# 注册
class Register(APIView):
    def post(self, request):
        account = request.data.get('account')
        password = request.data.get('password')
        data = {}
        if re.match(r'^1[3-9]\d{9}$', account):
            data['phone'] = account
        elif re.match(r'^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$', account):
            data['email'] = account
        else:
            data['username'] = account
        data['password'] = password
        ser = UserSerializer(data=data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200, 'msg': '注册成功', 'data': ser.data})
        return Response({'code': 400, 'msg': '注册失败', 'data': ser.errors})


# 登录
class UserView(APIView):
    def post(self, request):
        username = request.data.get("username")
        password = request.data.get("password")
        # | Q(email=username)
        aa = UserModel.objects.filter(Q(phone=username) | Q(username=username) | Q(email=username)).first()
        if aa is None:
            return Response({"code": 400, "msg": "用户不存在"})
        elif aa.password == password:
            data = {
                "id": aa.id,
                "username": username,
                # "token": tooljwt.getToken(aa.id, username)
            }
            return Response({"code": 200, "msg": "登录成功", "data": data})
        else:
            return Response({"code": 400, "msg": "密码错误"})